 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=139 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Command objects
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='AbstractAction,AbstractValidatingWebAction,AbstractWebAction,Action,AddMessage,MyActionAddMessage,MyActionFetchMessages,ShowRecentMessages,WebAction,Command,JSP,servlet,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Command objects</div>

<div class='main-body'>
 
<br>It is a common practice to define an interface for processing a user's
request at a high level of abstraction. This corresponds roughly to the
Command pattern described in <i>Design Patterns</i>.

<h4>Example</h4>
<a href='http://www.web4j.com/web4j/javadoc/hirondelle/web4j/action/Action.html'><tt>Action</tt></a>
is an interface which
<ul>
<li>executes a business operation (validates input, interacts with the datastore,
and places appropriate model objects in request scope or session scope)</li>
<li>sets the identity of the resource which will render the model objects (typically
a JSP)</li>
<li>controls when a redirect should be sent to the browser</li>
</ul>

<P>Here is its implementation :
<br>
<PRE>

<span class='keyword'>package</span> hirondelle.web4j.action;

<span class='keyword'>import</span> hirondelle.web4j.model.AppException;

<span class='comment'>/**
 &lt;span class="highlight"&gt;
 Process an HTTP request, and return a {@link ResponsePage}.
 &lt;/span&gt;

 &lt;P&gt;&lt;b&gt;This interface is likely the most important 
 abstraction in WEB4J.&lt;/b&gt; Almost every feature implemented by the programmer will 
 need an implementation of this interface. 
 
 &lt;P&gt;Typically, one of the &lt;em&gt;ActionXXX&lt;/em&gt; abstract base classes are used to 
 build implementations of this interface.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>interface</span> Action {
  
  <span class='comment'>/**
  Execute desired operation.
   
  &lt;P&gt;Typical operations include : 
  &lt;ul&gt;
  &lt;li&gt;validate user input
  &lt;li&gt;interact with the database 
  &lt;li&gt;place required objects in the appropriate scope
  &lt;li&gt;set the appropriate {@link ResponsePage}.
  &lt;/ul&gt;
  
  &lt;P&gt;Returns an identifier for the resource (for example a JSP) which 
  will display the end result of this &lt;tt&gt;Action&lt;/tt&gt; (using either a 
  forward or a redirect).
  */</span>
  ResponsePage execute() <span class='keyword'>throws</span> AppException;
  
}
 
</PRE>
<br>
<P><tt>Action</tt> implementations perform similar tasks. These
tasks should be placed in an Abstract Base Class (ABC), which will simplify
concrete implementations. The WEB4J tool defines several such ABC's :
<ul>
<li><tt><a href='http://www.web4j.com/web4j/javadoc/hirondelle/web4j/action/ActionImpl.html'>ActionImpl</a></tt> - 
collects various <tt>protected final</tt> utility methods needed by many <tt>Action</tt> classes. <tt>ActionImpl</tt> in 
turn forms a base class for the <tt>ActionTemplateXXX</tt> classes.
<li><tt><a href='http://www.web4j.com/web4j/javadoc/hirondelle/web4j/action/ActionTemplateListAndEdit.html'>ActionTemplateListAndEdit</a></tt> - 
shows a listing, and a form to edit items in the listing
<li><tt><a href='http://www.web4j.com/web4j/javadoc/hirondelle/web4j/action/ActionTemplateShowAndApply.html'>ActionTemplateShowAndApply</a></tt> - 
shows a form for editing a single item
<li><tt><a href='http://www.web4j.com/web4j/javadoc/hirondelle/web4j/action/ActionTemplateSearch.html'>ActionTemplateSearch</a></tt> - 
shows a form for entering search criteria
</ul>

The various <tt>ActionTemplateXXX</tt> classes implement the <a href="TopicActione01b-2.html">template method</a> design pattern.
The application programmer chooses a particular template based in the desired style of user interface. 

<P>Example of a concrete <tt>Action</tt> :
<br>
<PRE>

<span class='keyword'>package</span> hirondelle.fish.main.discussion;

<span class='keyword'>import</span> java.util.*;
<span class='keyword'>import</span> java.util.regex.Pattern;
<span class='keyword'>import</span> hirondelle.web4j.database.DAOException;
<span class='keyword'>import</span> hirondelle.web4j.database.Db;
<span class='keyword'>import</span> hirondelle.web4j.database.SqlId;
<span class='keyword'>import</span> hirondelle.web4j.model.AppException;
<span class='keyword'>import</span> hirondelle.web4j.model.ModelCtorException;
<span class='keyword'>import</span> hirondelle.web4j.model.ModelFromRequest;
<span class='keyword'>import</span> hirondelle.web4j.request.RequestParameter;
<span class='keyword'>import</span> hirondelle.web4j.action.ResponsePage;
<span class='keyword'>import</span> hirondelle.web4j.request.RequestParser;
<span class='keyword'>import</span> hirondelle.web4j.action.ActionTemplateShowAndApply;
<span class='keyword'>import</span> hirondelle.fish.util.TemplatedPage;
<span class='keyword'>import</span> hirondelle.web4j.BuildImpl;

<span class='comment'>/**
 List comments, and add new ones.
 
 &lt;P&gt;Comments are listed, along with a paging mechanism.
 
 @sql statements.sql
 @view view.jsp
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> CommentAction <span class='keyword'>extends</span> ActionTemplateShowAndApply {
  
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>final</span> SqlId FETCH_RECENT_COMMENTS =  <span class='keyword'>new</span> SqlId(<span class='literal'>"FETCH_RECENT_COMMENTS"</span>);
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>final</span> SqlId ADD_COMMENT =  <span class='keyword'>new</span> SqlId(<span class='literal'>"ADD_COMMENT"</span>);
  
  <span class='comment'>/** Constructor. */</span>
  <span class='keyword'>public</span> CommentAction(RequestParser aRequestParser){
    <span class='keyword'>super</span>(FORWARD, REDIRECT, aRequestParser);
  }
  
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>final</span> RequestParameter COMMENT_BODY = RequestParameter.withLengthCheck(
    <span class='literal'>"Comment Body"</span>
   );

  <span class='comment'>/** Used for the paging mechanism. */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>final</span> RequestParameter PAGE_SIZE = RequestParameter.withRegexCheck(
    <span class='literal'>"PageSize"</span>, Pattern.compile(<span class='literal'>"(&#092;&#092;d){1,4}"</span>)
   );
  <span class='comment'>/** Used for the paging mechanism. */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>final</span> RequestParameter PAGE_INDEX = RequestParameter.withRegexCheck(
    <span class='literal'>"PageIndex"</span>, Pattern.compile(<span class='literal'>"(&#092;&#092;d){1,4}"</span>)
  );
  
  <span class='comment'>/** Show the listing of comments, and a form for adding new messages. */</span>
  <span class='keyword'>protected</span> <span class='keyword'>void</span> show() <span class='keyword'>throws</span> AppException {
    addToRequest(ITEMS_FOR_LISTING, fetchRecentComments());
  }
  
  <span class='comment'>/** Ensure user input can build a new {@link Comment}.  */</span>
  <span class='keyword'>protected</span> <span class='keyword'>void</span> validateUserInput() <span class='keyword'>throws</span> AppException {
    <span class='keyword'>try</span> {
      ModelFromRequest builder = <span class='keyword'>new</span> ModelFromRequest(getRequestParser());
      <span class='comment'>/*
        This is an example of using a time which, for testing purposes,
        can be made independent of the true system time. The value of 
        the 'now' variable depends on the implementation of TimeSource.
       */</span>
      <span class='keyword'>long</span> now = BuildImpl.forTimeSource().currentTimeMillis();
      fComment = builder.build(
        Comment.<span class='keyword'>class</span>, getLoggedInUserName(), COMMENT_BODY, <span class='keyword'>new</span> Date(now)
      );
    }
    <span class='keyword'>catch</span> (ModelCtorException ex){
      addError(ex);
    }
  }
  
  <span class='comment'>/** Add a new {@link Comment} to the database. */</span>
  <span class='keyword'>protected</span> <span class='keyword'>void</span> apply() <span class='keyword'>throws</span> AppException {
    <span class='comment'>//no possibility of a duplicate error.
</span>    addNew(fComment);
  }
  
  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> Comment fComment;
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> ResponsePage FORWARD = TemplatedPage.get(
    <span class='literal'>"Discussion"</span>, <span class='literal'>"view.jsp"</span>, CommentAction.<span class='keyword'>class</span>
  );
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> ResponsePage REDIRECT =  <span class='keyword'>new</span> ResponsePage(
    <span class='literal'>"CommentAction.show?PageIndex=1&PageSize=10"</span>
  );
  
  <span class='comment'>/*
   Here, the DAO methods are not in a separate class, but simply regular methods of 
   this Action. This reasonable since the methods are short, and they do not make 
   this Action class significantly more complex. 
  */</span>
  
  <span class='comment'>/**
   Return an immutable {@link List} of recent {@link Comment} objects.
  
   &lt;P&gt;The definition of what constitutes "recent" is left deliberately vague, to 
   allow various versions of "recent" - last 5 messages, messages entered over 
   the last N days, etc.
  */</span>
  <span class='keyword'>private</span> List&lt;Comment&gt; fetchRecentComments() <span class='keyword'>throws</span> DAOException {
    <span class='keyword'>return</span> Db.list(Comment.<span class='keyword'>class</span>, FETCH_RECENT_COMMENTS);
  }

  <span class='comment'>/**
   Add &lt;tt&gt;aNewComment&lt;/tt&gt; to the database. No duplicates are possible.
  
   @param aNewComment to be added to the datastore.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>void</span> addNew(Comment aNewComment) <span class='keyword'>throws</span> DAOException {
    Object[] params = { 
      aNewComment.getUserName(), aNewComment.getBody(), aNewComment.getDate() 
    };
    Db.edit(ADD_COMMENT, params);
  }
}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction0df2-2.html?Id=107'>Refactor large Controllers </a> <br>
 
  
  <a href='TopicAction703a-2.html?Id=138'>Parse parameters into domain objects</a> <br>
 
  
  <a href='TopicActione01b-2.html?Id=164'>Template method</a> <br>
 
  
  <a href='TopicAction8130-2.html?Id=181'>Forward versus redirect</a> <br>
 
  
  <a href='TopicAction5f31-2.html?Id=188'>A Web App Framework - WEB4J</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='139'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=139 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
